class Project < ActiveRecord::Base
  belongs_to :owner, :class_name => "User", :foreign_key => "owner_id", :dependent => :destroy
    
  has_many :milestones
  has_many :activities
  has_many :messages
  
  accepts_nested_attributes_for :milestones
  
  has_many :designations
  accepts_nested_attributes_for :designations
  has_many :users, :through => :designations
  
  has_many :logs, :order => "created_at DESC"
  
  attr_accessor :users_emails
  
  after_create :create_designations
  
  validates_presence_of :name
  validates_length_of :name, :within => 2..60
  
  before_validation :assert_duplicated_users
  
  def assert_duplicated_users
    users = User.all
    
    designations.each do |designation|
      users.each do |user| 
        if user.email == designation.user.email
          designation.user = user
        end
      end
    end
  end
  
  after_update :send_warning_email_if_marked_for_deletion
  
  def send_warning_email_if_marked_for_deletion
    if delete_at_changed?
      Delayed::Job.enqueue ProjectDeletionMailerJob.new(id, Thread.current[:user_id]) unless delete_at.blank?
    end
  end
  
  def create_designations
    designations.create(:user_id => Thread.current[:user_id], :admin => true)
    
    return unless @users_emails
    
    @users_emails.split(",").each do |logon|
      user = User.find_or_create_by_email(logon.strip)
      if user.valid? and designations.create(:user => user)
        #Delayed::Job.enqueue InvitationMailerJob.new(Thread.current[:user_id], user.id, id)
      else
        @errors = user.errors
        raise ActiveRecord::InvalidRecord
      end
    end
  end
  
  def mark_for_deletion
    !delete_at.nil?
  end
  
  def mark_for_deletion=(condition)
    if condition == 1.to_s
      self.delete_at = 1.week.from_now if delete_at.nil?
    else
      self.delete_at = nil
    end
  end
  
  def to_param
    "#{id}-#{name.gsub(/[^a-z0-9]+/i, '-')}".downcase
  end
  
  def to_s
    name.titleize
  end
end
